package com.donger.boms.service.Impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donger.boms.entity.ProductBom;
import com.donger.boms.exception.BizException;
import com.donger.boms.mapper.ProductBomMapper;
import com.donger.boms.service.ProductBomService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class ProductBomServiceImpl extends ServiceImpl<ProductBomMapper, ProductBom> implements ProductBomService {
    private final ProductBomMapper bomMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean upload(MultipartFile file,String bomNumber) {
        ImportParams params =new ImportParams();
        params.setTitleRows(3);
        params.setHeadRows(1);
        List<ProductBom> list;
        try {
            list= ExcelImportUtil.importExcel(
                    file.getInputStream(),
                    ProductBom.class,params
            );
        }catch (Exception e){
            throw new BizException("服务器异常");
        }
        list.stream().peek(i ->{
            if(i.getParentNumber() == null){
                i.setParentNumber("0");
            }
            i.setBomNumber(bomNumber);
        }).collect(Collectors.toList());
        list.removeIf(s -> s.getNumber()==null);
        this.saveBatch(list);
        return true;
    }

    @Override
    public List<ProductBom> queryList(String number) {
        return bomMapper.queryList(number);
    }
}
